using System;
using System.Text;
using System.Text.RegularExpressions;

namespace Tyng
{
    /// <summary>
    /// String function library
    /// </summary>
    public static class StringHelper
    {
        /// <summary>
        /// Split a string that has quoted pieces (ie. a csv file)
        /// </summary>
        /// <param name="toSplit">String to split</param>
        /// <param name="separator">Separator between pieces</param>
        /// <param name="maxValues">Maximum number of values to return in teh array</param>
        /// <returns>Split values</returns>
        public static string[] QuotedSplit(string toSplit, string separator, int maxValues)
        {
            if (toSplit == null)
                throw new ArgumentNullException("toSplit");

            if (toSplit.Length == 0)
                return new String[1] { String.Empty };

            string sepRegex = Regex.Escape(separator);

            MatchCollection matches = Regex.Matches(toSplit, "(^|(?<=[" + sepRegex + "]))((?<quote>\"(?<data>((\"\")|[^\"])*?)\")|(?<data>[^" + sepRegex + "]*?))([" + sepRegex + "]|$)");

            string[] pieces = new string[Math.Min(matches.Count, maxValues)];

            for (int i = 0; i < pieces.Length; i++)
            {
                pieces[i] = matches[i].Groups["data"].Value;

                //fixed escaped quotes
                if (matches[i].Groups["quote"].Success)
                    pieces[i] = pieces[i].Replace("\"\"", "\"");
            }

            //if more matches found than requested, append left over string to last item
            if (matches.Count > pieces.Length)
            {
                Match lastMatch = matches[pieces.Length];
                pieces[pieces.Length - 1] += toSplit.Substring(lastMatch.Index + lastMatch.Length);
            }

            return pieces;
        }

        /// <summary>
        /// Split a string that has quoted pieces (ie. a csv file)
        /// </summary>
        /// <param name="toSplit">String to split</param>
        /// <param name="separator">Separator between pieces</param>
        /// <returns>Split values</returns>
        public static string[] QuotedSplit(string toSplit, string separator)
        {
            return QuotedSplit(toSplit, separator, int.MaxValue);
        }


    }
}
